import cors from "koa2-cors"
import koaBody from "koa-bodyparser"
import Koa from "koa";

// import {error} from "./error"
// import {response} from "./response"
import {errorMsg, successMsg} from "../utils/errorMsg"


/**
 * 跨域处理
 */

const mdCors = cors({
    origin: '*',
    credentials: true,
    allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']
});

/**
 * 参数解析
 * https://github.com/koajs/bodyparser
 */
const mdKoaBody = koaBody({
    enableTypes: ['json', 'form', 'text', 'xml'],
    formLimit: '56kb',
    jsonLimit: '1mb',
    textLimit: '1mb',
    strict: true
});

/**
 * 统一返回格式
 */
// const mdResHandler = response();
/**
 * 错误处理
 */
// const mdErrorHandler = error();

/**
 * 通用返回操作
 * */
const response = async (ctx: Koa.Context, next: Koa.Next) => {
    await next()
    // console.log(ctx.status)

    if (ctx.status === 200) {
        ctx.body = {
            code: 1,
            result: ctx.body,
            msg: successMsg.Instance().getSuccessMsg() ?? "success"
        }
    } else {
        ctx.body = {
            code: -1,
            result: ctx.body,
            msg: errorMsg.Instance().getErrorMsg() ?? "fail"
        }
    }
}

export default [
    mdKoaBody,
    mdCors,
    response
    // mdResHandler,
    // mdErrorHandler,
]